<?php

namespace App\Repositories;

use App\Account;
use App\Email\MailParse;
use App\Email\Parse;
use App\Email\Pop3;
use App\WatchLog;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;

class EmailRepostory
{
    protected $email;

    public function __construct()
    {
        $this->email = new \PHPMailer();
        $this->parse = new Parse();
        $this->parseEmail = new MailParse();
        $this->user = \Auth::user();
        //七牛配置
        $this->accessKey = 'PB0TU6Tx3k3SuuIztN_YzClhV33NtSbvTmDz0x8L';
        $this->secretKey = 'WkON2t5t1v4Q17RTfJa6Ud0BXefZ6XDg_rtqcJ0g';
        $this->bucket = 'anyuzhe';
        $this->domain = 'http://7xsdnt.com1.z0.glb.clouddn.com/';
    }

    public function collectionList()
    {
        $accountid = Account::where('accountaddress',$this->user->email)->pluck('accountid');
        $emails = $this->getEmails($accountid,1);
        foreach ($emails as $k=>$email) {
            $_email = $this->pullEmail($email->messageid);
            $data[$k] = $this->parseEmail->parse($_email);
            $data[$k]['messageid'] = $email->messageid;
            $_watch = WatchLog::where('messageid',$email->messageid)->first();
            $data[$k]['watch'] = $_watch?1:0;
        }
        return $data;
//        $data = $this->pop3();
//        return $data;
    }

    protected function parseTest($file)
    {
        $set = new \ezcMailFileSet(array($file));
        $parser = new \ezcMailParser();
        $mail = $parser->parseMail( $set );
        echo formatMail( $mail[0] );
    }

    public function show($messageid)
    {
        $email = $this->pullEmail($messageid);
        $watch = new WatchLog();
        $watch->watchEmail($messageid);
        if($email) {
            $data = $this->parseEmail->parseAll($email);
        }
        return $data;
    }

    public function outboxList()
    {
        $accountid = Account::where('accountaddress',$this->user->email)->pluck('accountid');
        $emails = $this->getEmails($accountid,2);
        foreach ($emails as $k=>$email) {
            $_email = $this->pullEmail($email->messageid);
            $data[$k] = $this->parseEmail->parse($_email);
            $data[$k]['messageid'] = $email->messageid;
        }
        return $data;
//        $data = $this->pop3();
//        return $data;
    }

    public function getAdd($messageid,$fileName){
        $email = $this->pullEmail($messageid);
        if($email) {
            $data = $this->parseEmail->parseAdd($email,$fileName);
            dd($data);
        }
    }

    protected function pullEmail($messageid)
    {
        $email = $this->getEmail($messageid);
        if($email) {
            $account = Account::where('accountid', $email->messageaccountid)->first();
            if($account) {
                $folderName = $this->getFolder($account->accountaddress);
                $address = $this->getTureAddress($folderName, $email->messagefilename);
                $_email = $this->readEmail($address);
            }
        }
        return $_email;
    }

    protected function getFolder($email)
    {
        $pattern = "/(.*?)@.*/ims";
        preg_match($pattern, $email, $arr);
        if(!empty($arr[1]))
            return $arr[1];
        return false;
    }

    protected function getTureAddress($folderName,$address)
    {
        $substr = substr($address,1,2);
        $address = 'D:\\hMailServer\\Data\mail.sxqtwy.com\\'.$folderName.'\\'.$substr.'\\'.$address;
        return $address;
    }

    protected function getEmails($id,$type)
    {
        $flow = DB::table('messages');
        if ($id) {
            $flow = $flow->where('messageaccountid', $id);
        }
        if ($type == 1) {
            $flow = $flow->where('messagelocked', 1);
        }
        elseif ($type==2){
            $flow = $flow->where('messagelocked', 0);
        }
        return $flow->get();
    }

    protected function getEmail($id)
    {
        return DB::table('messages')->where('messageid', $id)->first();
    }

    public function readEmail($address)
    {
        if(File::exists($address)) {
            $content = File::get($address);
            return $content;
        }else{
            return false;
        }
    }
    public function write()
    {
        return view('email.write');
    }

    public function send($request)
    {
        $user = \Auth::user();
        $this->email->isSMTP();
//        $this->email->Host = 'smtp.163.com';  // Specify main and backup SMTP servers
//        $this->email->SMTPAuth = true;                               // Enable SMTP authentication
//        $this->email->Username = 'anyuzheqs1@163.com';                 // SMTP username
//        $this->email->Password = 'a2361326';                           // SMTP password
//        $this->email->SMTPSecure = 'ssl';                            // Enable TLS encryption, `ssl` also accepted
//        $this->email->Port = 25;                                             // TCP port to connect to
//        $this->email->SMTPSecure = false;
        $this->email->Host = 'mail.sxqtwy.com';  // Specify main and backup SMTP servers
        $this->email->SMTPAuth = true;                               // Enable SMTP authentication
        $this->email->Username = $user->email;                 // SMTP username
        $this->email->Password = $user->email_password;                           // SMTP password
        $this->email->SMTPSecure = 'ssl';                            // Enable TLS encryption, `ssl` also accepted
        $this->email->Port = 25;                                    // TCP port to connect to
        $this->email->SMTPSecure = false;



        $this->email->setFrom($user->email, $user->name);
        $this->email->addReplyTo($user->email, $user->name);
//        $this->email->setFrom('anyuzheqs1@163.com', 'Mailer');
//        $this->email->addReplyTo('anyuzheqs1@163.com','暗语者');               // Name is optional
        $this->email->addAddress($request->toEmail, $request->toName);     // Add a recipient
//        $this->email->addCC('cc@example.com');
//        $this->email->addBCC('bcc@example.com');

//        $this->email->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
//        $this->email->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
        $this->email->isHTML(true);                                  // Set email format to HTML

        $this->email->Subject = $request->title;
        $this->email->Body    = $request->body;
        $this->email->CharSet = "utf-8";
        if(!$this->email->send()) {
            echo 'Message could not be sent.';
            echo 'Mailer Error: ' . $this->email->ErrorInfo;
        } else {
            echo 'Message has been sent';
        }
    }

    public function pop3(){
        error_reporting(E_ALL ^ (E_WARNING | E_NOTICE));

        //使用pop3
        $host = "mail.sxqtwy.com";
//        $user = 'ttt@mail.sxqtwy.com';
//        $pwd  = 'asasas';
        $user = $this->user->email;;
        $pwd  = $this->user->email_password;
        $dmail = new Pop3($host, $user, $pwd);
        $msg = $dmail->pop3();
        $ret = $msg;
//        dump($user);
//        dump($pwd);
//        dump($msg);
        if( strpos($msg, 'read complete')!==FALSE ){
            $mail_list_arr = $dmail->getContent();
            $mail_list_arr = array_reverse($mail_list_arr);
//            dump($mail_list_arr);
            foreach($mail_list_arr  as $k=>$v ){
//                $_data = $this->parseEmail->parse($v);
//                if($_data['images']) {
//                    $_data['images'] = $this->emailPicture($_data['images']);
//                    $_data =  $this->imgagesChange($_data);
//                }
                dump($_data = $this->parse->parse($v));
                $data[] = $_data;
            }
        }
        return $data;
    }

    public function imgagesChange($_data)
    {
        $data = $_data;
        foreach ($_data['images'] as $k=>$image) {
            $data['body'] = str_replace('cid:'.$k,$image,$data['body']);
        }
        return $data;
    }
    public function emailPicture($images)
    {
        foreach ($images as &$image) {
            $image = $this->uploadQN($image);
        }
        return $images;
    }

    public function uploadQN($filePath,$name)
    {
        require_once '../app/Lib/Qnsdk/autoload.php';
        // 需要填写你的 Access Key 和 Secret Key
//        $accessKey = 'PB0TU6Tx3k3SuuIztN_YzClhV33NtSbvTmDz0x8L';
//        $secretKey = 'WkON2t5t1v4Q17RTfJa6Ud0BXefZ6XDg_rtqcJ0g';
//        $bucket = 'anyuzhe';
//        $domain = 'http://7xsdnt.com1.z0.glb.clouddn.com/';

        $auth = new Auth($this->accessKey, $this->secretKey);
// 构建 UploadManager 对象
        $uploadMgr = new UploadManager();
// 生成上传Token
        $token = $auth->uploadToken($this->bucket);
        $key = $name;
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
        if ($err !== null) {
            return false;
        } else {
            return $this->domain.$ret['key'];
        }
    }

    public function parseBackup($content)
    {
        //---------------------------标题-------------------------TODO 没写完 备用
        // 中文标题的处理
        if( preg_match('/Subject: =\?([^?]+)\?B\?([^?]+)\?=/i', $v, $subject) ){
            $title = base64_decode($subject[2]);
            $title = $subject[1]=='gbk'||$subject[1]=='gb2312' ? iconv('gbk', 'utf-8', $title) : $title;
        }
        // 英文标题
        else if( preg_match('/Subject: (.*?)\r\n/i', $v, $subject) ){
            $title = $subject[1];
        }
        else{
            $title = '邮件标题';
        }
        preg_match('/From: [^<]+<(.*?)>/i', $v, $from);
        preg_match('/Date: (.*?)\r\n/i', $v, $date);
        //---------------------------正文-------------------------

        //-------------------------------------------------------

        $email['title'] = $title;
        $email['from'] = $from[1];
        $email['time'] = $date[1];
        $email['data'] = $content;
        return $email;
    }


//        define(EML_FILE_PATH, './yjdata/');

//if ($filename == '') $filename = '21724696_niuyufu@qiaodazhao.com_ZC4422-r7GMz_R9QF3K6XUhmJOXd4c.eml';
//if ($filename == '') $filename = '21724696_niuyufu@qiaodazhao.com_ZC3218-dGquMgm7ytdF6HQgpSReC4c.eml';
//if ($filename == '') $filename = '163.eml';
//if ($filename == '') $filename = '166.eml';
//if ($filename == '') $filename = 'nyf.eml';
//if ($filename == '') $filename = 'email_header_icon.eml';
//        if ($filename == '') $filename = '20141230133705.eml';
//
//        $eml_file = EML_FILE_PATH . $filename;
//
//        if (!($content = fread(fopen(EML_FILE_PATH . $filename, 'rb'), filesize(EML_FILE_PATH . $filename))))
//            die('File not found (' . EML_FILE_PATH . $filename . ')');

//标题内容
    
}